package com.gjy.util.poi;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gjy.util.poi.entity.AuditField;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-07-14 09:12:48
 */
public class ExcelToSqlListener extends AnalysisEventListener<AuditField> {

    private static final Logger log = LoggerFactory.getLogger(ExcelToSqlListener.class);
    private static final List<String> DATA = new ArrayList<>();
    private static final String SQL_TEMPLATE_DOCUMENT_TYPE = "UPDATE SETTLE.SUPPLIER_DATA SET DOCUMENT_TYPE='%s' WHERE SUPPLIER_CODE='%s'";
    private static final String SQL_TEMPLATE_SUPPLIER_CATEGORY = "UPDATE SETTLE.SUPPLIER_DATA SET SUPPLIER_CATEGORY='%s' WHERE SUPPLIER_CODE='%s'";

    private static final String WRITE_SQL = "D:\\code\\java\\microservice_spc\\utils-all\\util-service\\src\\test\\resources\\poi\\write\\";

    @Override
    public void invoke(AuditField auditField, AnalysisContext analysisContext) {
        String sql = String.format(SQL_TEMPLATE_DOCUMENT_TYPE, auditField.getUpstreamValue(), auditField.getUpstreamKey());
        DATA.add(sql);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("{}", "SQL_TEMPLATE_DOCUMENT_TYPE 生成完成");
        String fileName = WRITE_SQL + "DOCUMENT_TYPE.sql";
        try {
            FileUtils.writeLines(new File(fileName), StandardCharsets.UTF_8.name(), DATA, ";\n", true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
